//
//  CoreDataHandle.m
//  CoreDataExercise
//
//  Created by Bang-guo on 15/7/10.
//  Copyright (c) 2015年 guobang. All rights reserved.
//

#import "CoreDataHandle.h"

@implementation CoreDataHandle

+(CoreDataHandle *)shareCoreData {
    
    static CoreDataHandle *coreData = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        coreData = [[CoreDataHandle alloc] init];
        
    });
    
    return coreData;
    
}

-(void)insert:(NSString *)entityName withPhoto:(NSString *)photo withName:(NSString *)name withRating:(NSString *)rating withRecommended_reason:(NSString *)recommended_reason withAddress:(NSString *)address withArrival_type:(NSString *)arrival_type withOpening_time:(NSString *)opening_time withTel:(NSString *)tel withPlaceId:(NSString *)placeId withDescriptionP:(NSString *)descriptionP withType:(NSString *)type withLat:(NSString *)lat withLng:(NSString *)lng {
    
    NSEntityDescription *entytyDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    NearbyDetailCDM *nearby = [[NearbyDetailCDM alloc] initWithEntity:entytyDescription insertIntoManagedObjectContext:self.managedObjectContext];
    nearby.photo = photo;
    nearby.name = name;
    nearby.rating = [NSString stringWithFormat:@"%@", rating];
    nearby.recommended_reason = recommended_reason;
    nearby.address = address;
    nearby.arrival_type = arrival_type;
    nearby.opening_time = opening_time;
    nearby.tel = tel;
    nearby.placeId = [NSString stringWithFormat:@"%@", placeId];
    nearby.descriptionP = descriptionP;
    nearby.type = [NSString stringWithFormat:@"%@", type];
    nearby.lat = [NSString stringWithFormat:@"%@", lat];
    nearby.lng = [NSString stringWithFormat:@"%@", lng];
    
    
    [self saveContext];
    
    
    
    
    
}



-(NSArray *)select:(NSString *)entityName withKey:(NSString *)key withValue:(id)value withSort:(NSString *)sort {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    request.predicate = predicate;
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sort ascending:YES];
    
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        
        NSLog(@"error = %@", error);
        
    }
    return array;
    
    
}

-(NSArray *)selectAll:(NSString *)entityName {
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        
        NSLog(@"error = %@", error);
        
    }
    return array;
}

-(void)deleteData:(NSString *)entityName withKey:(NSString *)key withValue:(id)value {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        
        NSLog(@"error = %@", error);
        
    }
    
    for (NearbyDetailCDM *near in array) {
        
        [self.managedObjectContext deleteObject:near];
        
        
    }
    [self saveContext];
    
}
/*
-(void)updata:(NSString *)entityName withKey:(NSString *)key withValue:(id)value withModle:(Person *)person {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", key, @"%@"], value];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        
        NSLog(@"error = %@", error);
        
    }
    
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
    
    Person *personTemp = [[Person alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
    personTemp = [array firstObject];
    personTemp.name = person.name;
    personTemp.tel = person.tel;
    personTemp.sex = person.sex;
    
    [self saveContext];
    
    
}
*/

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.guobang.CoreDataExercise" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CommonFrame" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataExercise.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}



@end
